#!/usr/bin/env python

# System env test (squid, havp, unzip, wget......)
# Timing job
# Black site Trigger
    # black site analyse trigger
    # diff current black
    # sync to core manager site

from twisted.internet import reactor
from twisted.internet import threads
from twisted.internet import task
from twisted.web import server
from twisted.python import log
import VirusWallConfig
import VirusWallConfig
import VirusWallCore
import VirusWallCgi
import sys
import os


def run_cron_job():
    update_blackList_job = task.LoopingCall(VirusWallCore.update_blacklist)
    update_blackList_job.start(VirusWallConfig.UPDATE_BLACKLIST_INTERVAL)
    
    update_virus_pattern_job = task.LoopingCall(VirusWallCore.update_virus_pattern)
    update_virus_pattern_job.start(VirusWallConfig.UPDATE_VIRUS_PATTERN_INTERVAL)

    log_marking = task.LoopingCall(VirusWallCore.marking_log)
    log_marking.start(VirusWallConfig.LOGMARKING_INTERVAL)

    #squid_log_roate_job = task.LoopingCall(VirusWallCore.squid_log_rotate)
    #squid_log_roate_job.start(VirusWallConfig.SQUID_LOG_ROATE_INTERVAL)

def main():
    # starting log
    log.startLogging(sys.stdout)
    log.msg(VirusWallCore.banner())
    
    # init and test
    VirusWallCore.init_conf()
    
    # OK put cron job
    run_cron_job()
    
    # Check to enable or disable WEB manager
    if VirusWallConfig.WEB:
        site_root = VirusWallCgi.makePageChild()
        site = server.Site( site_root , logPath=os.path.join(
        VirusWallConfig.HTTP_LOGS, 'vw_access.log' ) )
        #define http server bind ipaddress and port
        reactor.listenTCP( int( VirusWallConfig.WEB_MANAGER_PORT ) , site ,
        interface=VirusWallConfig.WEB_MANAGER_LISTEN_IP ) #IGNORE:E0611
    else:
        pass
    
    #Now analyze havp access log in thread
    tail_havp_access_log = threads.deferToThread(VirusWallCore.tail_file, VirusWallConfig.HAVP_ACCESS_LOG_FILEPATH)
    #tail_havp_access_log.addCallback(VirusWallCore.analyze_havp_access_log)
    print dir(tail_havp_access_log)

    # reactor !!!!!
    reactor.run()

if __name__ == '__main__':
    main()
